<script>
  import {
    SSEWebSocket
  } from '@/utils/websocket.js';
  import {
    createMessage
  } from '@/utils/websocketMessages.js';
  import {
    onMounted
  } from 'vue'

  // onMounted(() => {
  //   if (plus.os.name === 'Android') {
  //     plus.android.runtimeMainActivity().setActivityResultListener((requestCode, resultCode, data) => {
  //       if (requestCode === 1001 && resultCode === plus.android.resolveConstant(
  //           'android.app.Activity.RESULT_OK')) {
  //         const Uri = plus.android.importClass('android.net.Uri');
  //         const RingtoneManager = plus.android.importClass('android.media.RingtoneManager');

  //         const ringtoneUri = data.getStringExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
  //         if (ringtoneUri) {
  //           const uri = Uri.parse(ringtoneUri);
  //           handleRingtoneResult(uri.toString());
  //         } else {
  //           handleRingtoneResult(null);
  //         }
  //       }
  //     });
  //   }
  // })

  // unction handleRingtoneResult(uri) {
  //   // 传递给 RingtoneSetting.vue 或全局状态管理
  //   uni.$emit('ringtone-selected', uri);
  // }

  export default {
    onLaunch: function() {
      console.log('应用启动，初始化 WebSocket 连接')

      const accessToken = uni.getStorageSync('deviceNo'); // 替换为实际获取的 accessToken
      this.sseClient = new SSEWebSocket(accessToken);

      // 将WebSocket实例暴露给全局，让其他页面可以访问
      getApp().globalData = getApp().globalData || {};
      getApp().globalData.sseClient = this.sseClient;

      // 监听消息（服务端发送消息时触发）
      this.sseClient.on('message', (msg) => {
        console.log('【收到消息】', msg); // 打印消息内容
        this.handleMessage(msg);
      });

      // 监听连接打开
      this.sseClient.on('open', () => {
        console.log('WebSocket 已连接');
      });

      // 监听连接关闭
      this.sseClient.on('close', (res) => {
        console.log('WebSocket 已关闭:', res);
      });

      // 监听错误
      this.sseClient.on('error', (err) => {
        console.error('WebSocket 错误:', err);
      });
    },
    onShow: function() {
      console.log('App Show')
    },
    onHide: function() {
      console.log('App Hide')
    },
    onUnload() {
      // 应用关闭时发送退出通知消息
      if (this.sseClient && this.sseClient.isConnected) {
        try {
          const exitMessage = createMessage('EXIT');
          this.sseClient.send(exitMessage);
          console.log('已发送应用退出通知消息:', exitMessage);
        } catch (e) {
          console.error('发送退出通知消息失败:', e);
        }
      }

      // 手动关闭连接
      if (this.sseClient) {
        this.sseClient.close();
        console.log('WebSocket 已手动关闭');
      }
    },
  }
</script>

<style>
  /*每个页面公共css */
  /* 隐藏H5平台所有滚动条 */
  * {
    box-sizing: border-box;
  }

  ::-webkit-scrollbar {
    display: none !important;
    /* 完全隐藏 */
    width: 0 !important;
    /* 宽度置0 */
    height: 0 !important;
    /* 高度置0 */
  }
</style>